<template>
  <div class="shopping-cart-container">
    <div class="page-header">
      <h1>购物车</h1>
      <p>共 {{ cartItems.length }} 件商品</p>
    </div>

    <div class="cart-content" v-if="cartItems.length > 0">
      <!-- 购物车列表 -->
      <div class="cart-list">
        <el-card>
          <div class="cart-header">
            <el-checkbox 
              v-model="selectAll" 
              @change="handleSelectAll"
              :indeterminate="isIndeterminate"
            >
              全选
            </el-checkbox>
            <span class="header-item product">商品信息</span>
            <span class="header-item price">单价</span>
            <span class="header-item quantity">数量</span>
            <span class="header-item total">小计</span>
            <span class="header-item actions">操作</span>
          </div>
          
          <div class="cart-items">
            <div 
              v-for="item in cartItems"
              :key="item.id"
              class="cart-item"
            >
              <el-checkbox 
                :model-value="selectedItems.includes(item.id)"
                @change="handleItemSelect(item.id, $event)"
              />
              
              <div class="product-info">
                <el-image
                  :src="item.product.image || '/default-product.jpg'"
                  fit="cover"
                  class="product-image"
                  @click="goToProduct(item.product.id)"
                />
                <div class="product-details">
                  <h3 class="product-name" @click="goToProduct(item.product.id)">
                    {{ item.product.name }}
                  </h3>
                  <p class="product-desc">{{ item.product.description }}</p>
                  <div class="product-specs" v-if="item.specs">
                    <el-tag 
                      v-for="(value, key) in item.specs"
                      :key="key"
                      size="small"
                      type="info"
                    >
                      {{ key }}: {{ value }}
                    </el-tag>
                  </div>
                </div>
              </div>
              
              <div class="item-price">
                <span class="current-price">¥{{ item.product.price }}</span>
                <span v-if="item.product.originalPrice > item.product.price" class="original-price">
                  ¥{{ item.product.originalPrice }}
                </span>
              </div>
              
              <div class="item-quantity">
                <el-input-number
                  v-model="item.quantity"
                  :min="1"
                  :max="item.product.stock"
                  @change="updateQuantity(item)"
                />
              </div>
              
              <div class="item-total">
                <span class="total-price">¥{{ (item.product.price * item.quantity).toFixed(2) }}</span>
              </div>
              
              <div class="item-actions">
                <el-button 
                  type="text" 
                  icon="Star"
                  @click="favoriteProduct(item.product)"
                >
                  收藏
                </el-button>
                <el-button 
                  type="text" 
                  icon="Delete"
                  @click="removeItem(item)"
                  class="delete-btn"
                >
                  删除
                </el-button>
              </div>
            </div>
          </div>
        </el-card>
      </div>

      <!-- 结算区域 -->
      <div class="checkout-section">
        <el-card>
          <div class="checkout-summary">
            <div class="summary-item">
              <span>已选商品：</span>
              <span class="highlight">{{ selectedItems.length }} 件</span>
            </div>
            <div class="summary-item">
              <span>商品总价：</span>
              <span class="highlight">¥{{ totalPrice.toFixed(2) }}</span>
            </div>
            <div class="summary-item" v-if="discount > 0">
              <span>优惠金额：</span>
              <span class="discount">-¥{{ discount.toFixed(2) }}</span>
            </div>
            <div class="summary-item total">
              <span>应付总额：</span>
              <span class="final-price">¥{{ finalPrice.toFixed(2) }}</span>
            </div>
          </div>
          
          <div class="checkout-actions">
            <el-button 
              type="primary" 
              size="large" 
              :disabled="selectedItems.length === 0"
              @click="goToCheckout"
            >
              去结算 ({{ selectedItems.length }})
            </el-button>
          </div>
        </el-card>
      </div>
    </div>

    <!-- 空购物车 -->
    <div class="empty-cart" v-else>
      <el-empty description="购物车是空的">
        <el-button type="primary" @click="goToMall">去逛逛</el-button>
      </el-empty>
    </div>

    <!-- 推荐商品 -->
    <div class="recommended-products" v-if="recommendedProducts.length > 0">
      <el-card>
        <template #header>
          <span>为您推荐</span>
        </template>
        <div class="recommended-grid">
          <div 
            v-for="product in recommendedProducts"
            :key="product.id"
            class="recommended-item"
            @click="goToProduct(product.id)"
          >
            <el-image
              :src="product.image || '/default-product.jpg'"
              fit="cover"
              class="recommended-image"
            />
            <div class="recommended-info">
              <h4>{{ product.name }}</h4>
              <div class="recommended-price">¥{{ product.price }}</div>
              <el-button 
                type="primary" 
                size="small"
                @click.stop="addToCart(product)"
              >
                加入购物车
              </el-button>
            </div>
          </div>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  getCart,
  updateCartItem,
  removeCartItem,
  getRecommendedProducts,
  addToCart as apiAddToCart,
  favoriteProduct as apiFavoriteProduct
} from '@/api/mall'

const router = useRouter()

// 响应式数据
const cartItems = ref([])
const recommendedProducts = ref([])
const selectedItems = ref([])
const selectAll = ref(false)

// 计算属性
const isIndeterminate = computed(() => {
  return selectedItems.value.length > 0 && selectedItems.value.length < cartItems.value.length
})

const totalPrice = computed(() => {
  return cartItems.value
    .filter(item => selectedItems.value.includes(item.id))
    .reduce((total, item) => total + item.product.price * item.quantity, 0)
})

const discount = computed(() => {
  // 这里可以根据优惠规则计算折扣
  return 0
})

const finalPrice = computed(() => {
  return totalPrice.value - discount.value
})

// 获取购物车数据
const loadCart = async () => {
  try {
    const response = await getCart()
    if (response.code === 200) {
      cartItems.value = response.data || []
    }
  } catch (error) {
    console.error('获取购物车失败:', error)
    ElMessage.error('获取购物车失败')
  }
}

// 获取推荐商品
const loadRecommendedProducts = async () => {
  try {
    const response = await getRecommendedProducts({ limit: 8 })
    if (response.code === 200) {
      recommendedProducts.value = response.data || []
    }
  } catch (error) {
    console.error('获取推荐商品失败:', error)
  }
}

// 全选/取消全选
const handleSelectAll = (checked) => {
  if (checked) {
    selectedItems.value = cartItems.value.map(item => item.id)
  } else {
    selectedItems.value = []
  }
}

// 选择/取消选择商品
const handleItemSelect = (itemId, checked) => {
  if (checked) {
    selectedItems.value.push(itemId)
  } else {
    const index = selectedItems.value.indexOf(itemId)
    if (index > -1) {
      selectedItems.value.splice(index, 1)
    }
  }
  
  // 更新全选状态
  selectAll.value = selectedItems.value.length === cartItems.value.length
}

// 更新商品数量
const updateQuantity = async (item) => {
  try {
    await updateCartItem(item.id, { quantity: item.quantity })
  } catch (error) {
    console.error('更新数量失败:', error)
    ElMessage.error('更新数量失败')
  }
}

// 删除商品
const removeItem = async (item) => {
  try {
    await ElMessageBox.confirm(`确认要删除 ${item.product.name} 吗？`, '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await removeCartItem(item.id)
    ElMessage.success('删除成功')
    loadCart()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除商品失败:', error)
      ElMessage.error('删除商品失败')
    }
  }
}

// 收藏商品
const favoriteProduct = async (product) => {
  try {
    await apiFavoriteProduct(product.id)
    ElMessage.success('已添加收藏')
  } catch (error) {
    console.error('收藏失败:', error)
    ElMessage.error('收藏失败')
  }
}

// 添加到购物车
const addToCart = async (product) => {
  try {
    await apiAddToCart({
      productId: product.id,
      quantity: 1
    })
    ElMessage.success('已加入购物车')
    loadCart()
  } catch (error) {
    console.error('加入购物车失败:', error)
    ElMessage.error('加入购物车失败')
  }
}

// 跳转到商品详情
const goToProduct = (productId) => {
  router.push(`/mall/product/${productId}`)
}

// 跳转到商城
const goToMall = () => {
  router.push('/mall')
}

// 去结算
const goToCheckout = () => {
  if (selectedItems.value.length === 0) {
    ElMessage.warning('请选择要结算的商品')
    return
  }
  
  router.push({
    path: '/mall/checkout',
    query: {
      items: selectedItems.value.join(',')
    }
  })
}

// 页面加载
onMounted(() => {
  loadCart()
  loadRecommendedProducts()
})
</script>

<style lang="scss" scoped>
.shopping-cart-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding: 20px;
}

.page-header {
  text-align: center;
  margin-bottom: 30px;
  
  h1 {
    font-size: 32px;
    color: #303133;
    margin: 0 0 10px 0;
  }
  
  p {
    color: #606266;
    font-size: 16px;
    margin: 0;
  }
}

.cart-content {
  max-width: 1200px;
  margin: 0 auto;
  display: flex;
  gap: 20px;
  
  .cart-list {
    flex: 1;
    
    .cart-header {
      display: flex;
      align-items: center;
      padding: 16px;
      background-color: #f8f9fa;
      border-bottom: 1px solid #e9ecef;
      
      .header-item {
        &.product {
          flex: 1;
          margin-left: 20px;
        }
        
        &.price,
        &.quantity,
        &.total,
        &.actions {
          width: 100px;
          text-align: center;
        }
      }
    }
    
    .cart-items {
      .cart-item {
        display: flex;
        align-items: center;
        padding: 20px 16px;
        border-bottom: 1px solid #f0f0f0;
        
        &:last-child {
          border-bottom: none;
        }
        
        .product-info {
          flex: 1;
          display: flex;
          gap: 12px;
          margin-left: 20px;
          
          .product-image {
            width: 80px;
            height: 80px;
            border-radius: 4px;
            cursor: pointer;
          }
          
          .product-details {
            flex: 1;
            
            .product-name {
              margin: 0 0 8px 0;
              font-size: 16px;
              font-weight: 500;
              cursor: pointer;
              color: #409eff;
              
              &:hover {
                text-decoration: underline;
              }
            }
            
            .product-desc {
              margin: 0 0 8px 0;
              color: #606266;
              font-size: 14px;
              overflow: hidden;
              text-overflow: ellipsis;
              white-space: nowrap;
            }
            
            .product-specs {
              display: flex;
              gap: 4px;
              flex-wrap: wrap;
            }
          }
        }
        
        .item-price {
          width: 100px;
          text-align: center;
          
          .current-price {
            color: #e6a23c;
            font-weight: bold;
          }
          
          .original-price {
            display: block;
            color: #909399;
            font-size: 12px;
            text-decoration: line-through;
          }
        }
        
        .item-quantity {
          width: 100px;
          text-align: center;
        }
        
        .item-total {
          width: 100px;
          text-align: center;
          
          .total-price {
            color: #e6a23c;
            font-weight: bold;
            font-size: 16px;
          }
        }
        
        .item-actions {
          width: 100px;
          text-align: center;
          
          .delete-btn {
            color: #f56c6c;
          }
        }
      }
    }
  }
  
  .checkout-section {
    width: 300px;
    
    .checkout-summary {
      margin-bottom: 20px;
      
      .summary-item {
        display: flex;
        justify-content: space-between;
        margin: 12px 0;
        
        .highlight {
          color: #e6a23c;
          font-weight: bold;
        }
        
        .discount {
          color: #67c23a;
        }
        
        &.total {
          font-size: 18px;
          font-weight: bold;
          border-top: 1px solid #e9ecef;
          padding-top: 12px;
          
          .final-price {
            color: #e6a23c;
            font-size: 20px;
          }
        }
      }
    }
    
    .checkout-actions {
      text-align: center;
    }
  }
}

.empty-cart {
  text-align: center;
  padding: 60px 0;
}

.recommended-products {
  max-width: 1200px;
  margin: 40px auto 0;
  
  .recommended-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
    gap: 20px;
    
    .recommended-item {
      cursor: pointer;
      transition: transform 0.3s;
      
      &:hover {
        transform: translateY(-2px);
      }
      
      .recommended-image {
        width: 100%;
        height: 150px;
        border-radius: 4px;
        margin-bottom: 8px;
      }
      
      .recommended-info {
        h4 {
          margin: 0 0 8px 0;
          font-size: 14px;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
        
        .recommended-price {
          color: #e6a23c;
          font-weight: bold;
          margin-bottom: 8px;
        }
      }
    }
  }
}

@media (max-width: 768px) {
  .shopping-cart-container {
    padding: 10px;
  }
  
  .cart-content {
    flex-direction: column;
    
    .checkout-section {
      width: 100%;
    }
  }
  
  .cart-header {
    display: none;
  }
  
  .cart-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
    
    .product-info {
      margin-left: 0;
    }
    
    .item-price,
    .item-quantity,
    .item-total,
    .item-actions {
      width: auto;
      text-align: left;
    }
  }
}
</style>
